<?php
namespace app\data_magic\extension;

/**
 * 过滤器
 * 处理用户输入的搜索条件
 * 为了保证安全，并且简化逻辑，这个类中只能有处理单条搜索条件的方法
 * @param array $fields 每个搜索条件允许包含多个字段，以数组的形式输入字段的名称
 * @param int|string $value 用户输入的值，允许为数组
 * @return string 条件为空时返回空字符串
 */
class Filter
{
    public function keyword($fields,$value)
    {
        $where_array=[];
        foreach($fields as $field_name){
            $where_array[]=" `$field_name` like '%$value%' ";
        }
        if(!$where_array){
            return "";
        }
        return "(".implode(" ) OR ( ",$where_array).")";
    }
    public function date($fields,$value)
    {
        $start_time=date_create_from_format("Y-m-d H:i:s",$value." 00:00:00")->getTimestamp();
        $end_time=date_create_from_format("Y-m-d H:i:s",$value." 24:00:00")->getTimestamp();
        $where_array=[];
        foreach($fields as $field_name){
            $where_array[]=" `$field_name` >= $start_time and `$field_name` <= $end_time ";
        }
        if(!$where_array){
            return "";
        }
        return "(".implode(" ) AND ( ",$where_array).")";
    }
    public function timePeriods($fields,$value)
    {
        $start_time=$value["start"];
        $end_time=$value["end"];
        $where_array=[];
        foreach($fields as $field_name){
            $sub_where = $start_time ? " `$field_name` >= $start_time " : "" ;
            if($end_time){
                $sub_where_2 = " `$field_name` <= $end_time " ;
                $sub_where .= $sub_where ? "and".$sub_where_2 : $sub_where_2 ;
            }
            if($sub_where){
                $where_array[]=$sub_where;
            }
        }
        if(!$where_array){
            return "";
        }
        return "(".implode(" ) AND ( ",$where_array).")";
    }
}
